package com.adtech.farmProducts.activities.activity;

import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.adtech.farmProducts.R;
import com.adtech.farmProducts.base.BaseActivity;
import com.adtech.farmProducts.utils.Constants;
import com.google.gson.Gson;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.UUID;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Time:2020/7/8
 * Created by xiaocz
 * Describe
 */
public class BluetoothActivity extends BaseActivity {


    @BindView(R.id.tv_content)
    TextView tv_content;

    private BluetoothAdapter mBluetoothAdapter;

    @Override
    protected int getLayoutSourceId() {
        return R.layout.activity_bluetooth;
    }

    @Override
    protected void initData() {
        super.initData();
        init();
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); // null:表示不支持蓝牙
        boolean enabled = mBluetoothAdapter.isEnabled(); // true:处于打开状态, false:处于关闭状态
        tv_content.setText(String.valueOf(enabled));
    }

    BluetoothDevice bluetooth;
    private List<HashMap> blueList;

    @OnClick({R.id.btn_ok, R.id.btn_get_blue, R.id.btn_search, R.id.btn_in})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_ok:
                startActivityForResult(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE), 1);
                break;
            case R.id.btn_get_blue:
                Set<BluetoothDevice> bondedDevices = mBluetoothAdapter.getBondedDevices(); // 获取已经配对的蓝牙设备
                blueList = new ArrayList<>();
                for (BluetoothDevice bluetoothDevice : bondedDevices) {
                    bluetooth = bluetoothDevice;
                    HashMap<Object, Object> blueHashMap = new HashMap<>();
                    blueHashMap.put("blue_name", bluetoothDevice.getName());
                    blueHashMap.put("blue_address", bluetoothDevice.getAddress());
                    blueList.add(blueHashMap);
                }
                tv_content.setText(new Gson().toJson(blueList));
                break;
            case R.id.btn_search:
                //如果当前在搜索，就先取消搜索
                if (mBluetoothAdapter.isDiscovering()) {
                    mBluetoothAdapter.cancelDiscovery();
                }
                //开启搜索
                mBluetoothAdapter.startDiscovery();
                break;

            case R.id.btn_in:
                BluetoothManager mBluetoothManager = (BluetoothManager) mContext.getSystemService(Context.BLUETOOTH_SERVICE);
                BluetoothAdapter mBluetoothAdapter = mBluetoothManager.getAdapter();
                //获取所需地址
                String mDeviceAddress = bluetooth.getAddress();
                mBluetoothGatt = bluetooth.connectGatt(mContext, false, mGattCallback, BluetoothDevice.TRANSPORT_LE);
                break;

        }
    }

    BluetoothGattCharacteristic alertLevel;
    BluetoothGatt mBluetoothGatt;

    // BLE回调操作
    private BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {

        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            super.onConnectionStateChange(gatt, status, newState);
            if (newState == BluetoothProfile.STATE_CONNECTED) {
                // 连接成功
                System.out.println("---------连接成功");
                //gatt.discoverServices();//必须有，可以让onServicesDiscovered显示所有Services
                mBluetoothGatt.discoverServices();
            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                // 连接断开
                System.out.println("---------连接断开" + status);
            }
        }

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {//发现服务，在蓝牙连接的时候会调用
            List<BluetoothGattService> list = mBluetoothGatt.getServices();
            for (BluetoothGattService bluetoothGattService : list) {
                String str = bluetoothGattService.getUuid().toString();
                Log.e("str", " ：" + str);
                List<BluetoothGattCharacteristic> gattCharacteristics = bluetoothGattService
                        .getCharacteristics();
                for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
                    Log.e("gattCharacteristic", " ：" + gattCharacteristic.getUuid());
                    //  49535343-1e4d-4bd9-ba61-23c647249616 49535343-fe7d-4ae5-8fa9-9fafd205e455
                    if ("49535343-1e4d-4bd9-ba61-23c647249616".equals(gattCharacteristic.getUuid().toString())) {
                        alertLevel = gattCharacteristic;
                        Log.e("daole", alertLevel.getUuid().toString());
                    }
                }
            }
            enableNotification(gatt, alertLevel);//必须要有，否则接收不到数据
        }

        private void enableNotification(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            if (gatt == null || characteristic == null)
                return;
            mBluetoothGatt.setCharacteristicNotification(characteristic, true);
            BluetoothGattDescriptor descriptor = characteristic.getDescriptor(
                    UUID.fromString(Constants.CLIENT_CHARACTERISTIC_CONFIG));//SampleGattAttributes.CLIENT_CHARACTERISTIC_CONFIG
            descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
            mBluetoothGatt.writeDescriptor(descriptor);
            mBluetoothGatt.requestMtu(50);
        }

        @Override
        public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            super.onCharacteristicRead(gatt, characteristic, status);
            if (status == BluetoothGatt.GATT_SUCCESS) {
                // 收到的数据
                byte[] receiveByte = characteristic.getValue();
                System.out.println("----收到数据" + receiveByte);
            } else {
                Log.d("TAG", "onCharacteristicRead fail-->" + status);
            }
        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            super.onCharacteristicChanged(gatt, characteristic);
            StringBuilder sbu = new StringBuilder();
            for (int i = characteristic.getValue().length - 1; i > 0; i--) {
                int v = characteristic.getValue()[i - 1];
                sbu.append((char) v);
            }
            BigDecimal decimal = new BigDecimal(sbu.toString());
            decimal = decimal.setScale(2, BigDecimal.ROUND_UP);
            System.out.println(decimal.toString());
        }

        /**
         * 收到BLE终端写入数据回调
         * @param gatt
         * @param characteristic
         * @param status
         */
        @Override
        public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            super.onCharacteristicWrite(gatt, characteristic, status);
            if (status == BluetoothGatt.GATT_SUCCESS) {//写入成功
                Log.e("onCharacteristicWrite中", "写入成功");
            } else if (status == BluetoothGatt.GATT_FAILURE) {
                Log.e("onCharacteristicWrite中", "写入失败");
            } else if (status == BluetoothGatt.GATT_WRITE_NOT_PERMITTED) {
                Log.e("onCharacteristicWrite中", "没权限");
            }
        }

        @Override
        public void onDescriptorWrite(BluetoothGatt gatt,
                                      BluetoothGattDescriptor descriptor, int status) {
            super.onDescriptorWrite(gatt, descriptor, status);
            if (status == BluetoothGatt.GATT_SUCCESS) {

            }
        }

        @Override
        public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
            super.onReadRemoteRssi(gatt, rssi, status);
            if (status == BluetoothGatt.GATT_SUCCESS) {
            }
        }

        @Override
        public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
            super.onDescriptorRead(gatt, descriptor, status);
            Log.e("onCDescripticRead中", "数据接收了哦" + bytesToHexString(descriptor.getValue()));
            if (status == BluetoothGatt.GATT_SUCCESS) {
            }
        }
    };

    public String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            System.out.println(i + "-" + v);
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }

    //初始化特征
//    public void initBLE(BluetoothGatt gatt) {
//        if (gatt == null) {
//            return;
//        }
//        //遍历所有服务
//        for (android.bluetooth.BluetoothGattService BluetoothGattService : gatt.getServices()) {
//            Log.e(TAG, "--->BluetoothGattService" + BluetoothGattService.getUuid().toString());
//
//            //遍历所有特征
//            for (BluetoothGattCharacteristic bluetoothGattCharacteristic : BluetoothGattService.getCharacteristics()) {
//                Log.e("---->gattCharacteristic", bluetoothGattCharacteristic.getUuid().toString());
//
//                String str = bluetoothGattCharacteristic.getUuid().toString();
//                System.out.println("-------str:"+str);
//                if (str.equals(writeCharactUuid)) {
//                    //根据写UUID找到写特征
//                    mBluetoothGattCharacteristic = bluetoothGattCharacteristic;
//                } else if (str.equals(notifyCharactUuid)) {
//                    //根据通知UUID找到通知特征
//                    mBluetoothGattCharacteristicNotify = bluetoothGattCharacteristic;
//                }
//            }
//        }
//    }

    private void init() {
        // 设置广播信息过滤
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothDevice.ACTION_FOUND);//每搜索到一个设备就会发送一个该广播
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);//当全部搜索完后发送该广播
        filter.setPriority(Integer.MAX_VALUE);//设置优先级
        // 注册蓝牙搜索广播接收者，接收并处理搜索结果
        this.registerReceiver(receiver, filter);
    }

    List<BluetoothDevice> bluetoothList = new ArrayList<>();
    List<String> list =new ArrayList<>();

    BroadcastReceiver receiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(BluetoothDevice.ACTION_FOUND)) { //found device
                BluetoothDevice device = intent
                        .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                String str = device.getName() + "|" + device.getAddress();
                System.out.println("BlueTooth搜索到的设备:" + str);
                //如果List中没有str元素则返回-1
                if (list.indexOf(str) == -1){// 防止重复添加
                    bluetoothList.add(device);
                    list.add(str);
                }
            } else if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_STARTED)) {
                Toast.makeText(getBaseContext(), "正在扫描", Toast.LENGTH_SHORT).show();
            } else if (action
                    .equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) {
                Toast.makeText(getBaseContext(), "扫描完成，点击列表中的设备来尝试连接", Toast.LENGTH_SHORT).show();
                dialogListBlue();
            }
        }
    };

    private void dialogListBlue() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("请选择电子秤蓝牙");
        builder.setItems(list.toArray(new String[]{}), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                mBluetoothGatt = bluetoothList.get(which).connectGatt(mContext, true, mGattCallback, BluetoothDevice.TRANSPORT_LE);
                dialog.dismiss();
            }
        });
        builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.show();
    }
}
